<?php

//------------------------
// 资讯管理控制器
//-------------------------
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\Article as ArticleModel;
use app\common\model\ArticleClassify as ArticleClassifyModel;
use think\Db;
use think\Config;
use think\Image;

class Article extends AdminBase
{
    protected $article_model;
    protected $article_classify_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->article_model                 = new ArticleModel();
        $this->article_classify_model        = new ArticleClassifyModel();
    }



    // 资讯列表
    public function index(){
        $title = $this->request->param('title','','trim');
        $is_on   = $this->request->param('is_on',0,'intval');
        $is_examine   = $this->request->param('is_examine',0,'intval');
        $cid   = $this->request->param('cid',0,'intval');
        $start    = $this->request->param('start','','trim');
        $stop     = $this->request->param('stop','','trim');

        // 获取资讯分类树
        $acTree = $this->article_classify_model->getTree();
        $this->assign('acTree',$acTree);

        $where = array();
        if ($is_on) {
            $_is_on = $is_on == 2?0:1;
            $where['is_on'] = array('eq',$_is_on);
        }
        if ($is_examine) {
            $_is_examine = $is_examine == 2?0:1;
            $where['is_examine'] = array('eq',$_is_examine);
        }
        if ($title) {
             $where['title'] = array('like','%'.$title.'%');
        }
        if ($cid) {
             $where['cid'] = array('eq',$cid);
        }
        //日期搜索
        if ($start) {
            $_start = strtotime(date('Y-m-d 00:00:00', strtotime($start)));
            $where['update_time'] = array('egt',$_start);
        }
        if ($stop) {
            $_stop  = strtotime(date('Y-m-d 23:59:59', strtotime($stop)));
            $where['update_time'] = array('elt',$_stop);
        }
        if ($start && $stop) {
            $_start = strtotime(date('Y-m-d 00:00:00', strtotime($start)));
            $_stop  = strtotime(date('Y-m-d 23:59:59', strtotime($stop)));
            if ($_start > $_stop) {
                $_stop = $_start + 86400;
            }
            $where['update_time'] = array('between',array($_start,$_stop));
        }

        // 先根据资讯分类排序，再根据排序值排序
        $info = $this->article_model->order('cid,sort_num')->where($where)->paginate(5);

        $this->assign('title',$title);
        $this->assign('is_on',$is_on);
        $this->assign('is_examine',$is_examine);
        $this->assign('cid',$cid);
        $this->assign('start',$start);
        $this->assign('stop',$stop);
        $this->assign('info',$info);

        return $this->fetch('index');
    }


    // 添加页面
    public function add(){
        // 获取资讯分类树
        $acTree = $this->article_classify_model->getTree();
        $this->assign('acTree',$acTree);

    	return $this->fetch('add');
    }

    // 编辑页面
    public function edit(){
        $id = $this->request->param('id',0,'intval');
        $data =  $this->article_model->where("id",$id)->find();

        // 获取资讯分类树
        $acTree = $this->article_classify_model->getTree();
        $this->assign('acTree',$acTree);

        $this->assign('data',$data);
        return $this->fetch('edit');
    }

    /**
     * @desc 添加、编辑操作
     */
    public function add_proc() {
        $data = $this->request->param();
        $id = $this->request->param('id',0,'intval');

        $validate_result = $this->validate($data, 'Article.add');
        if ($validate_result !== true) {
            $this->error($validate_result);
        }

        // 初始化数据
        $now = time();
        $data['update_time'] = $now;

        if ($id) {
            // 编辑
            $res =  $this->article_model->allowField(true)->save($data,$data['id']);
            $act = '编辑';
        } else {
            // 添加
            $data['add_time'] = $now;
            $res =  $this->article_model->allowField(true)->save($data);
            $act = '添加';
        }

        if ($res === false) {
            // 记录日志
            // $logData = array('module' => '规则管理' , 'action' =>  '添加规则' , 'remark' => '添加规则失败' , 'status' => 0);
            // recordActionLog($logData);
            $this->error($this->article_model->getError());
        } else {
            // 记录日志
            // $logData = array('module' => '规则管理' , 'action' => '添加规则' , 'remark' => '分类编号：' . $id , 'status' => 1);
            // recordActionLog($logData);
            $this->success('资讯'.$act.'成功');
        }
    }

    // 编辑排序值
    public function edit_sort_num(){
        $data = $this->request->param();
        $validate_result = $this->validate($data, 'Article.sort_num');
        if ($validate_result !== true) {
            $this->error($validate_result);
        }
        // 编辑
        $data['update_time'] = time();
        $res =  $this->article_model->allowField(true)->save($data,$data['id']);
        if ($res === false) {
            // 记录日志
            // $logData = array('module' => '规则管理' , 'action' =>  '添加规则' , 'remark' => '添加规则失败' , 'status' => 0);
            // recordActionLog($logData);
            $this->error($this->article_model->getError());
        } else {
            // 记录日志
            // $logData = array('module' => '规则管理' , 'action' => '添加规则' , 'remark' => '分类编号：' . $id , 'status' => 1);
            // recordActionLog($logData);
            $this->success('排序值修改成功');
        }

    }

    // 改变审核状态
    function change_examine(){
        $data = $this->request->param();//halt($data);
        // 编辑
        $data['update_time'] = time();
        $res =  $this->article_model->allowField(true)->save($data,$data['id']);
        if ($res === false) {
            // 记录日志
            // $logData = array('module' => '规则管理' , 'action' =>  '添加规则' , 'remark' => '添加规则失败' , 'status' => 0);
            // recordActionLog($logData);
            $this->error($this->article_model->getError());
        } else {
            // 记录日志
            // $logData = array('module' => '规则管理' , 'action' => '添加规则' , 'remark' => '分类编号：' . $id , 'status' => 1);
            // recordActionLog($logData);
            $this->success('审核状态修改成功');
        }
    }

    // 改变发布状态
    function change_on(){
        $data = $this->request->param();//halt($data);
        // 编辑
        $data['update_time'] = time();
        $res =  $this->article_model->allowField(true)->save($data,$data['id']);
        if ($res === false) {
            // 记录日志
            // $logData = array('module' => '规则管理' , 'action' =>  '添加规则' , 'remark' => '添加规则失败' , 'status' => 0);
            // recordActionLog($logData);
            $this->error($this->article_model->getError());
        } else {
            // 记录日志
            // $logData = array('module' => '规则管理' , 'action' => '添加规则' , 'remark' => '分类编号：' . $id , 'status' => 1);
            // recordActionLog($logData);
            $this->success('发布状态修改成功');
        }
    }

    /**
     * @desc AJAX上传图片
     */
    public function uploadImage() {
        $id = $this->request->param('id',0,'intval');
        $path = $this->request->param('path','other','trim');

        if (!$id) {
            $this->error('缺少要上传图片的资讯id');
        }

        // 获取表单上传文件 
        $file = request()->file('image');

        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(Config::get('image_validate'))->move(Config::get('image_path') . $path);


        if($info){
            // 返回图片地址
            $return_url = showImage($path, $info->getSaveName());

            // 保存图名字到数据库
            $data['logo'] = $info->getSaveName();
            $data['update_time'] = time();
            $data['id'] = $id;

            $res =  $this->article_model->allowField(true)->save($data,$data['id']);

            $return = array('msg' => '上传成功','url'=>$return_url, 'code' => 1);
        }else{
            // 上传失败获取错误信息
            $return = array('msg' => $file->getError(), 'code' => 0);
        }
        echo json_encode($return);
    }

    // 资讯详情
    public function details(){
        $id = $this->request->param('id',0,'intval');

        $data = $this->article_model->get($id);

        $data['volume'] = strlen($data['content']);

        $this->assign('data',$data);
        return $this->fetch('details');
    }


    // 删除操作
    public function delete(){
        $id = $this->request->param('id',0,'intval');

        if (!$id) {
            $this->error('请选择需要删除的数据');
        }

        $where['is_delete'] = array('eq',1);
        $where['id'] = array('eq',$id);
        $res =  $this->article_model->where($where)->delete();

        if ($res === false) {
            // 记录日志
            // $logData = array('module' => '设备管理' , 'action' => '删除滚动广告' , 'remark' => '删除滚动广告失败，广告编号：' . $id , 'status' => 0);
            // recordActionLog($logData);
            $this->error($this->article_model->getError());
        } else{
            // 记录日志
            // $logData = array('module' => '设备管理' , 'action' => '删除滚动广告' , 'remark' => '广告编号：' . $id , 'status' => 1);
            // recordActionLog($logData);
            $this->success('删除成功');
        }
    }

    // 批量处理
    public function batch_proc(){
        $data = $this->request->param();

        $ids = implode(',',$data['ids']);
        $map['id']  = ['in',$ids];
        $type = $data['type'];

        switch ($type) {
            case 'delete':
                $successData = array();
                $failData = array();
                for ($i=0; $i < count($data['ids']); $i++) { 
                    $result = $this->_batch_delete($data['ids'][$i]);
                    if ($result) {
                        array_push($successData, $data['ids'][$i]);
                    } else {
                        array_push($failData, $data['ids'][$i]);
                    }
                }
                $success = implode(',',$successData);
                $fail   = implode(',',$failData);
                $this->success('删除成功id为：'.$success.'，删除失败id为：'.$fail);
                break;
            case 'shelves':
                $res = $this->article_model->where($map)->update(['is_on' => '0']);
                $act = '下架';
                break;
            case 'release':
                $res = $this->article_model->where($map)->update(['is_on' => '1']);
                $act = '发布';
                break;
            case 'disable':
                $res = $this->article_model->where($map)->update(['is_examine' => '0']);
                $act = '审核禁止';
                break;
            case 'pass':
                $res = $this->article_model->where($map)->update(['is_examine' => '1']);
                $act = '审核通过';
                break;

            default:
                $this->error('非法操作');
                break;
        }

        if ($res === false) {
            $this->error($this->article_model->getError());
        } else {
            $this->success('批量'.$act.'成功');
        }
    }

    // 批量删除>>调用
    private function _batch_delete($id){
        $where['is_delete'] = array('eq',1);
        $where['id'] = array('eq',$id);
        $res = $this->article_model->where($where)->delete();

        if ($res == false) {
           return false;
        } else {
            return true;
        }
    }

}